<?php
namespace Foxframe;

class Controller
{
	protected $token;
	protected $view;
	protected $em;
	protected $uri;

	public function __construct()
	{
		$this->view		= new View();
		$this->em		= Registry::get('entityManager');
		$this->uri		= Uri::getInstance();

		//verifica se o usuário está logado
// 		if (!isset($_SESSION[SESSION_LOGIN]['usuario'])
// 				&& $this->uri->get('controller') != 'job'
// 				&& ($this->uri->get('application') != 'Login'
// 						|| ($this->uri->get('method') != 'viewLogin'
// 						&& $this->uri->get('method') != 'logout'
// 						&& $this->uri->get('method') != 'validarLogin')))
// 		{
// 			if (isset($_SERVER['REDIRECT_QUERY_STRING']))
// 				$_SESSION[SESSION_LOGIN]['url']	= $_SERVER['REDIRECT_QUERY_STRING'];
// 			$this->redirect(BASE_PATH.'login/index/logout');
// 		}

// 		if (!$this->uri->hasAccess($this->uri->get('application'), $this->uri->get('controller'), $this->uri->get('method')))
// 		{
// 			$this->setFlash('Error', 'Erro', 'Você não possui acesso à esta funcionalidade');
// 			$this->redirect($this->uri->getOrigem());
// 		}

	}

	public function getView()
	{
		return $this->view;
	}

	public function returnAjax($application = null, $controller = null, $view = null)
	{
		header('Content-Type: text/html; charset=utf-8');

		if (empty($application))
			$application	= $this->uri->get('application');
		if (empty($controller))
			$controller		= $this->uri->get('controller');
		if (empty($view))
			$view			= $this->uri->get('method');

		echo $this->view->fetch('App/'.$application.'/View/'.$controller.'/'.$view.$this->view->extension);
		exit();
	}

	public function redirect($local = null)
	{
		header("Location:". $local);
		exit();
	}

	public function forward($application, $controller, $method)
	{
		$this->uri->set('application', $application);
		$this->uri->set('controller', $controller);
		$this->uri->set('method', $method);
	}

	public function getComponent($controller, $method)
	{
		$controle = $controller.'Controller';
		$instancia = new $controle($this->smarty);
		$instancia->$method();
		return $this->smarty->fetch($controller.'/view/'.$method.'.html');
	}

	public function setFlash($type, $title, $text)
	{
		return $_SESSION[$this->uri->get('application')]['flashMessage'] = array(
				'type'	=> $type,
				'title'	=> $title,
				'text'	=> addslashes($text)
		);
	}
}
